package com.huahai.config;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 针对不同的流量流控效果响应不同的页面
 *
 * */
@Component
public class BlockExceptionHandler implements
        com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler {
    //BlockException 异常接口,包含Sentinel的五个异常// FlowException 限流异常
    // DegradeException 降级异常
    // ParamFlowException 参数限流异常
    // AuthorityException 授权异常
    // SystemBlockException 系统负载异常
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        ResponseResult result  = null;
        if (e instanceof AuthorityException){
            result = new ResponseResult(409,"授权规则限制，无法访问！");
            response.getWriter().write(JSON.toJSONString(result));
        }
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class ResponseResult{
    private int code;
    private String message;
}
